import logging
import ssl

import urllib3
from geventhttpclient import HTTPClient
from locust import FastHttpUser, task, between
import csv
import random

from encrypt import encryptAES

# 配置日志（INFO级别，输出到控制台和文件）
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("locust_test.log"),  # 输出到文件
        logging.StreamHandler()  # 输出到控制台
    ]
)
logger = logging.getLogger("locust")
urllib3.disable_warnings()
urllib3.util.connection.HAS_IPV6 = False  # 禁用IPv6


class SolUser(FastHttpUser):
    wait_time = between(0.1, 0.5)
    users = []
    login_failed = False
    ssl_options = {
        "ssl_version": ssl.PROTOCOL_TLSv1_2,
        "ciphers": "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256"
    }

    def __init__(self, environment):
        super().__init__(environment)
        self.credentials = None
        self.getProductDetails_data = None

    def on_start(self):

        if not SolUser.users:
            try:
                logging.info("获取用户帐号文件，开始------")
                with open("token_gao.csv", "r") as f:
                    SolUser.users = list(csv.DictReader(f))
                self.getProductDetails_data = encryptAES({
                    "id": 800107098,
                })

            except Exception as e:
                logging.error(e)
                logging.error("获取用户帐号文件失败，终止------")
                exit(-1)
        # 随机选择账号
        self.credentials = random.choice(self.users)
        # logger.info(self.credentials)

    # @task
    # def step5_listAnchorGoods(self):
    #     data = {
    #         "dreamerLiveNo": "1020250720100004",
    #     }
    #     resp = self.client.post("/api/common/listAnchorGoods",
    #                             json=data,
    #                             headers={
    #                                 "Authorization": self.credentials["token"],
    #                                 "Content-Type": "application/json",
    #                                 "x-signature": encryptAES(data)
    #                             },
    #                             verify=False,  # 跳过证书验证
    #                             timeout=30
    #                             )
    #     # logging.info(resp.json())

    @task
    def step6_getProductDetails(self):
        data = {
            "id": 800107098,
        }
        resp = self.client.post("https://slbapi.sootoken.com.cn/api/newProduct/getProductDetails",
                                json=data,
                                headers={
                                    "Authorization": self.credentials["token"],
                                    "Content-Type": "application/json",
                                    "x-signature": self.getProductDetails_data
                                })
        logging.info(resp.json())
    #
    # @task
    # def step7_queryUserAddress(self):
    #     data = {
    #         "userId": self.credentials["userId"],
    #         "pageNum": 1,
    #         "pageSize": 100
    #     }
    #     resp = self.client.post("/api/address/queryUserAddress",
    #                             data=data,
    #                             headers={
    #                                 "Authorization": self.credentials["token"],
    #                                 "Content-Type": "application/x-www-form-urlencoded",
    #                                 "x-signature": encryptAES(data)
    #                             })
    #     # logging.info(resp.json())
    #
    # @task
    # def step8_payTypelist(self):
    #     data = {
    #         "modeCode": 2,
    #         "payMode": 1
    #     }
    #     resp = self.client.post("/api/payType/list",
    #                             json=data,
    #                             headers={
    #                                 "Authorization": self.credentials["token"],
    #                                 "Content-Type": "application/json",
    #                                 "x-signature": encryptAES(data)
    #                             })
    #     # logging.info(resp.json())
    #
    # @task
    # def step9_placeOrder(self):
    #     # logging.info(f"开始使用用户 >>>{self.credentials["userId"]}")
    #     # 测试
    #     # data = {
    #     #     "addressId": 1272408,
    #     #     "anchorId": 4883181,
    #     #     "buyerMessage": "",
    #     #     "quantity": 1,
    #     #     "repositoryId": 2480333,
    #     #     "roomNumber": 1120250719100012,
    #     #     "wlStatus": 0,
    #     #     "totalPrice": 35,
    #     #     "productId": 800008146,
    #     # }
    #
    #     data = {
    #         "addressId": 127240,
    #         "anchorId": 1261964,
    #         "buyerMessage": "",
    #         "quantity": 1,
    #         "repositoryId": 2844366,
    #         "roomNumber": 1020250720100004,
    #         "wlStatus": 0,
    #         "totalPrice": 1,
    #         "productId": 800109828,
    #     }
    #
    #     with self.client.post(
    #             "/api/order/placeOrder",
    #             data=data,
    #             headers={
    #                 "Authorization": self.credentials["token"],
    #                 "Content-Type": "application/x-www-form-urlencoded",
    #                 "x-signature": encryptAES(data)
    #             },
    #     ) as response:
    #         # logging.info('------------------------------------------------------------------------------------------------')
    #         placeOrderJson = response.json()
    #         # logging.info(placeOrderJson)
    #         if placeOrderJson["code"] == '200':
    #             order_num = placeOrderJson["data"]["order_num"]  # 提取 data.order_numf
    #             logging.info("订单号" + order_num)
    #             signOrderdata = {
    #                 "order_id": order_num
    #             }
    #             resp = self.client.post("/api/alipayment/signOrder",
    #                                     data=signOrderdata,
    #                                     headers={
    #                                         "Authorization": self.credentials["token"],
    #                                         "Content-Type": "application/x-www-form-urlencoded",
    #                                         "x-signature": encryptAES(signOrderdata)}
    #                                     )
    #             logging.info(resp.json())
    #         else:
    #             pass
    #             logging.info(f"生成订单失败,状态码:{placeOrderJson["message"]}")
